﻿using System.Collections.Generic;
using System.Linq;
using System.Net;

namespace Xfs
{
    public class XfsNetInnerComponent : XfsNetSocketComponent
    {

        public override bool IsOuter => false;
        public XfsSession? Client { get; set; }
        
        ///从字典中取Session, 如果没有则创建一个新的Session, 并且保存到会字典中
        public XfsSession Get()
        {
            if (this.Sessions.Count == 0)
            {
                XfsSession? session = this.SessionPool.Pop(this);
                if (session != null)
                {
                    session.Init();

                    this.Sessions.Add(session.InstanceId, session);
                }
            }
            return Sessions.Values.ToList()[0];
        }

        ///从地址缓存中取Session, 如果没有则创建一个新的Session, 并且保存到地址缓存中
        public XfsSession? Get(IPEndPoint ipEndPoint)
        {
            if (this.AdressSessions.TryGetValue(ipEndPoint, out XfsSession? session))
            {
                return session;
            }

            session = this.SessionPool.Pop(this);
            if (session != null)
            {
                session.Init();

                this.AdressSessions.Add(ipEndPoint, session);
            }

            return session;
        }

        public void Add(IPEndPoint ipEndPoint)
        {
            this.Remove(ipEndPoint);
            XfsSession? session = this.SessionPool.Pop(this);
            if (session != null)
            {
                session.Init();

                this.AdressSessions.Add(ipEndPoint, session);
            }
        }

        public void Remove(IPEndPoint ipEndPoint)
        {
            if (this.AdressSessions.TryGetValue(ipEndPoint, out XfsSession? session))
            {
                this.AdressSessions.Remove(ipEndPoint);
                this.SessionPool.Push(session);
            }
        }

    }
}